package com.oritsh.dicom.scu;

import com.oritsh.dicom.dcmtk.DcmtkInterface;
import com.oritsh.dicom.utils.DicomStreamHelper;
import org.dcm4che.data.Attributes;
import org.dcm4che.data.Tag;
import org.dcm4che.io.DicomInputStream;
import org.dcm4che.io.DicomOutputStream;
import org.dcm4che.net.Association;
import org.dcm4che.net.PDVInputStream;
import org.dcm4che.util.SafeClose;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-2-10
 * Time: 下午1:16
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
public class DcmtkTmpFileStore implements DicomStreamStore {

    private Map<String, File> cache = new HashMap<>();

    Logger logger = LoggerFactory.getLogger(DcmtkTmpFileStore.class);

    @PreDestroy
    public void cleanup() {
        for (Map.Entry<String, File> entry : cache.entrySet()) {
            entry.getValue().delete();
            cache.remove(entry.getKey());
        }
    }

    @Override
    public void store(Association as, Attributes fmi, PDVInputStream data) throws IOException {
        String iuid = fmi.getString(Tag.MediaStorageSOPInstanceUID);
        File file = File.createTempFile("dcmtk", iuid);
        DicomOutputStream out = new DicomOutputStream(file);
        try {
            DicomStreamHelper.writeToStream(out, fmi, data);
        } finally {
            SafeClose.close(out);
        }
        if (file.length() > 0) {
            File tmp = File.createTempFile("dcmtk", iuid);
            DcmtkInterface.imageDecode(file.getAbsolutePath(), tmp.getAbsolutePath());
            file.delete();
            cache.put(iuid, tmp);
        } else
            cache.put(iuid, file);
    }

    @Override
    public DicomInputStream fetch(String iuid) throws IOException {
        File file = cache.get(iuid);

        if (file == null || !file.exists())
            return null;
        logger.info("return from file:" + file.getAbsolutePath());
        return new DicomInputStream(file);
//        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
//            int len = in.available();
//            byte[] buffer = new byte[len];
//            in.read(buffer);
//            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
//            return new DicomInputStream(byteArrayInputStream);
//        }
    }

    @Override
    public DicomInputStream pop(String iuid) throws IOException {
        DicomInputStream in = fetch(iuid);
        File file = cache.get(iuid);
        cache.remove(iuid);
        file.delete();
        return in;
    }


}
